""" 编写对订单数据的增删改查 """
import json

from django.http import JsonResponse
from django.db.models import Q
from web.models import Order, Warehouse
from datetime import datetime
import logging

system_logger = logging.getLogger('system_log')


def order_search(request):
    """订单数据查询"""
    # 接收前端传递过来的值
    data = json.loads(request.body.decode("utf-8"))
    try:
        system_logger.info("__开始订单数据查询操作__")
        currentPage = data['currentPage']  # 当前界面
        pageSize = data['pageSize']  # 页面大小
        search = data['search']  # 关键字
        # 数据库中提取数据
        if search != '':
            # 模糊查询
            result_objects = Order.objects.filter((Q(goods__icontains=search) | Q(commander__icontains=search)
                                                   | Q(warehouse__warehouse_name__icontains=search)) & Q(is_delete=0))

            # 构建结果列表
            output = []
            for result in result_objects:
                if result.create_time is not None:
                    create_time = result.create_time.strftime("%Y-%m-%d")
                else:
                    create_time = None
                if result.end_time is not None:
                    end_time = result.end_time.strftime("%Y-%m-%d")
                else:
                    end_time = None
                data = {
                    'order_id': result.order_id,
                    'goods': result.goods,
                    'create_time': create_time,
                    'end_time': end_time,
                    'warehouse': result.warehouse.warehouse_name,
                    'commander': result.commander,
                    'state': result.state,
                    'remarks': result.remarks
                }
                output.append(data)

        else:
            # 执行关联查询，并选择相关字段
            result_objects = Order.objects.filter(is_delete=0).select_related('warehouse').values('order_id', 'goods',
                                                                                                  'create_time',
                                                                                                  'end_time',
                                                                                                  'warehouse__warehouse_name',
                                                                                                  'commander', 'state',
                                                                                                  'remarks')
            # 构建结果列表
            for result in result_objects:
                if result["create_time"] is not None:
                    result["create_time"] = result["create_time"].strftime("%Y-%m-%d")
                else:
                    result["create_time"] = None
                if result["end_time"] is not None:
                    result["end_time"] = result["end_time"].strftime("%Y-%m-%d")
                else:
                    result["end_time"] = None
            output = result_objects
            # 修改列表名称
            for item in output:
                item['warehouse'] = item.pop('warehouse__warehouse_name')
        # 计算总数
        count = result_objects.count()
        # 计算分页索引
        index_start = pageSize * (currentPage - 1)
        index_end = index_start + pageSize
        if index_start > count:
            system_logger.error("需要查询的订单信息页面大于订单数量__查询失败")
            return JsonResponse({'code': '1', 'msg': "查询失败，原因是分页参数错误"})
        else:
            data_list = output[index_start: index_end]
            data = {'data': data_list, 'total': count}
            if search != '':
                system_logger.info(f"与{search}关键字相关的订单信息查询操作__成功")
            else:
                system_logger.info("订单信息查询操作__成功")
            return JsonResponse({'code': '0', 'msg': "查询成功！", 'data': data})

    except Exception as e:
        # return JsonResponse({'code': '1', 'msg': "数据查询过程出错，具体原因：" + str(e)})
        system_logger.error(f"订单数据查询过程出错，具体原因：{e}__查询失败")
        return JsonResponse({'code': '1', 'msg': "查询失败！", 'data': "null"})


def get_warehouses(request):
    """仓库列表查询"""
    try:
        system_logger.info("__开始仓库列表数据查询操作__")
        result = Warehouse.objects.filter(is_delete=0).values('warehouse_id', 'warehouse_name', 'state')

        # 提取 warehouse_name 字段的值到一个字典中
        output = []
        for data in result:
            data_dict = {
                'warehouse_id': data["warehouse_id"],
                'warehouse_name': data["warehouse_name"],
                'warehouse_state': str(data["state"])
            }
            output.append(data_dict)
        system_logger.info("仓库列表数据查询操作__成功")
        return JsonResponse({'code': '0', 'msg': "查询成功！", 'data': output})

    except Exception as e:
        # return JsonResponse({'code': '1', 'msg': "数据查询过程出错，具体原因：" + str(e)})
        system_logger.error(f"仓库列表数据查询过程出错，具体原因：{e}__查询失败")
        return JsonResponse({'code': '1', 'msg': "查询失败！", 'data': "null"})


def get_orders(request):
    """订单列表查询"""
    try:
        system_logger.info("__开始订单列表数据查询操作__")
        result = Order.objects.filter(is_delete=0).values('order_id', 'state')

        # 提取 warehouse_name 字段的值到一个字典中
        output = []
        for data in result:
            data_dict = {
                'order_id': data["order_id"],
                'order_state': str(data["state"])
            }
            output.append(data_dict)
        system_logger.info("订单列表数据查询操作__成功")
        return JsonResponse({'code': '0', 'msg': "查询成功！", 'data': output})

    except Exception as e:
        # return JsonResponse({'code': '1', 'msg': "数据查询过程出错，具体原因：" + str(e)})
        system_logger.error(f"订单列表数据查询过程出错，具体原因：{e}__查询失败")
        return JsonResponse({'code': '1', 'msg': "查询失败！", 'data': "null"})


def order_add(request):
    """订单新增"""
    # 接收前端传递过来的值
    data = json.loads(request.body.decode("utf-8"))
    try:
        system_logger.info("__开始新增订单数据操作__")
        if data["end_time"] != "":
            end_time = data["end_time"]
            end_time = datetime.strptime(end_time, "%Y-%m-%dT%H:%M:%S.%fZ")

            end = end_time.strftime("%Y-%m-%d")
        else:
            end = None
        # 创建一个数据对象
        add_data = Order(
            goods=data['goods'],
            create_time=datetime.now(),
            end_time=end,
            commander=data['commander'],
            state=data['state'],
            remarks=data['remarks'],
            warehouse_id=data['warehouse_id']
        )
        add_data.save()
        system_logger.info("新增订单数据操作__成功")
        return JsonResponse({'code': '0', 'msg': "添加成功！", 'data': "null"})

    except Exception as e:
        # return JsonResponse({'code': '1', 'msg': "订单添加过程出错，具体原因：" + str(e)})
        system_logger.error(f"新增订单数据操作过程出错，具体原因：{e}__操作失败")
        return JsonResponse({'code': '1', 'msg': "添加失败！", 'data': "null"})


def order_update(request):
    """订单信息修改"""
    # 接收前端传递过来的值
    data = json.loads(request.body.decode("utf-8"))
    try:
        system_logger.info("__开始修改订单数据操作__")
        # 处理时间信息
        if data["end_time"] != "":
            end_time = data["end_time"]
            end_time = datetime.strptime(end_time, "%Y-%m-%dT%H:%M:%S.%fZ")

            end = end_time.strftime("%Y-%m-%d")
        else:
            end = None

        update_data = Order.objects.get(order_id=data['order_id'])
        update_data.goods = data['goods']
        update_data.end_time = end
        update_data.warehouse_id = data['warehouse_id']
        update_data.commander = data['commander']
        update_data.state = data['state']
        update_data.remarks = data['remarks']

        update_data.save()
        system_logger.info("修改订单数据操作__成功")
        return JsonResponse({'code': '0', 'msg': "修改成功！", 'data': "null"})
    except Exception as e:
        # return JsonResponse({'code': '1', 'msg': "订单信息修改过程出错，具体原因：" + str(e)})
        system_logger.error(f"修改订单数据操作过程出错，具体原因：{e}__操作失败")
        return JsonResponse({'code': '1', 'msg': "修改失败！", 'data': "null"})


def order_delete(request):
    """订单信息删除"""
    # 接收前端传递过来的值
    data = json.loads(request.body.decode("utf-8"))
    try:
        system_logger.info(f"__开始删除order_id为{data['order_id']}的订单数据操作__")
        delete_data = Order.objects.get(order_id=data['order_id'])

        # 查询需要删除的数据，没有删除，只是修改了is_delete和delete_time字段
        delete_data.is_delete = 1
        delete_data.delete_time = datetime.now()
        delete_data.save()
        system_logger.info(f"删除order_id为{data['order_id']}的订单数据操作__成功")
        return JsonResponse({'code': '0', 'msg': "删除成功！", 'data': "null"})
    except Exception as e:
        # return JsonResponse({'code': '1', 'msg': "订单信息删除过程出错，具体原因：" + str(e)})
        system_logger.error(f"删除order_id为{data['order_id']}的订单数据操作过程出错，具体原因：{e}__操作失败")
        return JsonResponse({'code': '1', 'msg': "删除失败！", 'data': "null"})


def getOrderInfo(request):
    """获取单个订单信息"""
    # 接收前端传递过来的值
    data = json.loads(request.body.decode("utf-8"))
    try:
        system_logger.info(f"__开始获取order_id为{data['order_id']}的订单数据操作__")
        result = Order.objects.filter(order_id=data['order_id']).values('order_id', 'goods', 'end_time', 'warehouse_id',
                                                                        'commander', 'state', 'remarks')

        # 提取 warehouse_name 字段的值到一个字典中
        for result_data in result:
            if result_data["end_time"] != "":
                end_time = result_data["end_time"].strftime("%Y-%m-%d")

            else:
                end_time = None
            data_dict = {
                'order_id': str(result_data["order_id"]),
                'goods': result_data["goods"],
                'end_time': end_time,
                'warehouse_id': str(result_data["warehouse_id"]),
                'commander': result_data["commander"],
                'state': result_data["state"],
                'remarks': result_data["remarks"]

            }
        system_logger.info(f"order_id为{data['order_id']}的订单数据获取操作__成功")
        return JsonResponse({'code': '0', 'msg': "查询成功！", 'data': data_dict})

    except Exception as e:
        # return JsonResponse({'code': '1', 'msg': "数据查询过程出错，具体原因：" + str(e)})
        system_logger.error(f"order_id为{data['order_id']}的订单数据获取过程出错，具体原因：{e}__操作失败")
        return JsonResponse({'code': '1', 'msg': "查询失败！", 'data': "null"})